package cn.ww.teach.knowledge.nioKnowledge;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Getter;
import lombok.Setter;


/**
 * Created by Wangwang on 2017/11/22.
 */
@Setter
@Getter
public class NettyClient {
    private int port;

    public NettyClient(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        //建立通道
        EventLoopGroup connectGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new ClientReadHandler());
            }
        });
        ChannelFuture cf = bootstrap.connect("127.0.0.1", port).sync();
        cf.channel().writeAndFlush(Unpooled.copiedBuffer("呼叫server".getBytes()));
        System.out.println("======================>>>>>>>>>>>>>>>client发送: 呼叫server");
        cf.channel().closeFuture().sync();
        connectGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        try {
            new NettyServer(8384).run();
            new NettyClient(8384).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
